package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.FriendsLiveAdapter;
import com.zmx.patientend.adapter.ReplayAdapter;
import com.zmx.patientend.listener.OnItemPictureClickListener;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.FriendsMessage;
import com.zmx.patientend.pojo.Give;
import com.zmx.patientend.pojo.Replay;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.utils.P;
import com.zmx.patientend.view.util.MySharedPreferences;
import com.zmx.patientend.view.util.NineGridTestLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class FriendsDetailsActivity extends BaseActivity {

    @BindView(R.id.head)
    CircleImageView head;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.context)
    TextView context;
    @BindView(R.id.live_number)
    TextView live_number;
    @BindView(R.id.nineTestlayout)
    NineGridTestLayout nineTestlayout;
    @BindView(R.id.user_time)
    TextView userTime;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.edit_message)
    EditText editMessage;
    @BindView(R.id.live)
    ImageView live;

    //点赞
    private GridView gridview;
    private FriendsLiveAdapter liveAdapter;

    RecyclerView reReplay;
    private String article_id;

    private List<Replay> lists;
    private ReplayAdapter adapter;

    private Replay replay_message;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_friends_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        article_id = this.getIntent().getStringExtra("article_id");
        replay_message = new Replay();
        gridview = findViewById(R.id.gridview);

        lists = new ArrayList<>();
        adapter = new ReplayAdapter(this);
        reReplay = findViewById(R.id.re_replay);
        reReplay.setLayoutManager(new LinearLayoutManager(this));
        reReplay.setAdapter(adapter);
        adapter.setListAndNotifyDataSetChanged(lists);

        bbsDetails();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    Log.e("图片路径", "图片路径" + msg.obj.toString());

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        if (object.getInt("code") == 1) {

                            Gson gson = new Gson();

                            JSONObject data = object.getJSONObject("data");
                            FriendsMessage fm = gson.fromJson(data.toString(), FriendsMessage.class);
                            JSONArray imgs = data.getJSONArray("picture");
                            List<String> imageList = new ArrayList<>();
                            for (int j = 0; j < imgs.length(); j++) {

                                Log.e("图片路径", "图片路径" + imgs.get(j).toString());

                                imageList.add(imgs.get(j).toString());

                            }

                            JSONArray imgs_live = data.getJSONArray("give");
                            List<Give> lives = new ArrayList<>();
                            for (int g=0;g<imgs_live.length();g++){

                                Give give = gson.fromJson(imgs_live.getJSONObject(g).toString(),Give.class);
                                lives.add(give);

                            }

                            fm.setGives(lives);
                            liveAdapter = new FriendsLiveAdapter(mActivity, lives);
                            gridview.setAdapter(liveAdapter);
                            if (imageList.size() > 0) {
                                live_number.setText(lives.size() + "人点赞");
                            }

                            fm.setPicture(imageList);

                            if (fm.getIs_give() == 1){
                                live.setImageResource(R.mipmap.waterflow_icon_like_normal_a);

                            }else{
                                live.setImageResource(R.mipmap.waterflow_icon_like_normal);
                            }

                            Glide.with(mActivity).load(fm.getAvatar()).into(head);
                            name.setText(fm.getName());
                            context.setText(fm.getContent());
                            nineTestlayout.setListener(new OnItemPictureClickListener() {
                                @Override
                                public void onItemPictureClick(int itemPostion, int i, String url, List<String> urlList, ImageView imageView) {

                                    Intent intent = new Intent(mActivity, ImagePreviewActivity.class);
                                    intent.putStringArrayListExtra("imageList", (ArrayList<String>) urlList);
                                    intent.putExtra(P.START_ITEM_POSITION, 0);
                                    intent.putExtra(P.START_IAMGE_POSITION, 0);
                                    ActivityOptions compat = ActivityOptions.makeSceneTransitionAnimation(mActivity, imageView, imageView.getTransitionName());
                                    startActivity(intent, compat.toBundle());

                                }
                            });
                            nineTestlayout.setItemPosition(0);
                            nineTestlayout.setSpacing(15);
                            nineTestlayout.setUrlList(fm.getPicture());


                            bbsReply();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        if (object.getInt("code") == 1) {

                            JSONArray array = object.getJSONArray("data");
                            Gson gson = new Gson();
                            for (int i = 0; i < array.length(); i++) {

                                Replay replay = gson.fromJson(array.getJSONObject(i).toString(), Replay.class);
                                lists.add(replay);

                            }

                            adapter.notifyDataSetChanged();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        if (object.getInt("code") == 1) {

                            replay_message.setAvatar(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, ""));
                            replay_message.setName(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            replay_message.setReplytime(format.format(new Date()));
                            lists.add(replay_message);
                            adapter.notifyDataSetChanged();
                            editMessage.setText("");
                            hideInput();

                        }
                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 4:
                    Log.e("数据","数据"+msg.obj.toString());
//                {"code":1,"msg":"点赞成功","data":true,"give":2}?

                    try {
                        JSONObject object = new JSONObject(msg.obj.toString());

                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1){

                            live.setImageResource(R.mipmap.waterflow_icon_like_normal_a);

                        }else{
                            live.setImageResource(R.mipmap.waterflow_icon_like_normal);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    public void bbsDetails() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("cmd", "bbsDetails");
        params.put("data[article_id]", article_id);
        params.put("data[member_id]", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.bbs/bbsDetails", params, handler, 1, 404);

    }

    public void bbsReply() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("data[article_id]", article_id);
        params.put("data[row]", 1 + "");
        params.put("data[number]", 10 + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.bbs/bbsReply", params, handler, 2, 404);

    }

    public void replyPost() {

        List<String> l = new ArrayList<>();
        l.add(article_id);
        l.add(editMessage.getText().toString());
        l.add(0 + "");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "replyPost");
        params.put("data[article_id]", article_id);
        params.put("data[content]", editMessage.getText().toString());
        params.put("data[fid]", 0 + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.bbs/entry", params, handler, 3, 404);

    }


    public void give() {

        List<String> l = new ArrayList<>();
        l.add(article_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "give");
        params.put("data[article_id]", article_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.bbs/entry", params, handler, 4, 404);

    }
    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }

    @OnClick({R.id.live, R.id.send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.live:

                give();

                break;
            case R.id.send:
                if (editMessage.getText().toString().equals("")) {
                    return;
                }
                replay_message.setContent(editMessage.getText().toString());
                replyPost();
                break;
        }
    }
}
